package org.monk.phishphans2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.SimpleAdapter;

public class PhishPhans2Reviews extends ListActivity {

	protected static String showdate;

	protected Map<String, String> group;
	protected JSONArray jArray;
	protected JSONObject jObject;

	public String api = "2.0";
	public String method = "pnet.reviews.query";
	public String arguments = "&showdate=";

	public String json;
	public PhishPhans2Parser jParser;

	public List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
	PhishPhans2Server server;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		showdate = (savedInstanceState == null) ? null
				: (String) savedInstanceState.getSerializable("showdate");
		if (showdate == null) {
			Bundle extras = getIntent().getExtras();
			showdate = extras != null ? extras.getString("showdate") : null;
		}

		setTitle("Reviews " + showdate);
		new SelectDataTask().execute();
		registerForContextMenu(getListView());
	}

	private class SelectDataTask extends
			AsyncTask<String, Void, List<Map<String, String>>> {
		private final ProgressDialog dialog = new ProgressDialog(
				PhishPhans2Reviews.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Loading data from web.");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Map<String, String>> doInBackground(final String... args) {

			PhishPhans2Server server = new PhishPhans2Server(getApplicationContext());
			String json = null;
			try {
				json = server.fetch(api, method, arguments + showdate,
						PhishPhans2SingleYearList.class.getSimpleName());
			} catch (IOException e) {
				e.printStackTrace();
			}
			PhishPhans2Parser jParser = new PhishPhans2Parser(json);
			groupData = jParser.parseJsonForReviews();

			return groupData;

		}

		// can use UI thread here
		protected void onPostExecute(final List<Map<String, String>> groupData) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			SimpleAdapter adapter = new SimpleAdapter(PhishPhans2Reviews.this,
					groupData, android.R.layout.simple_list_item_2,
					new String[] { "author", "review" }, new int[] {
							android.R.id.text1, android.R.id.text2 }) {
				public boolean areAllItemsEnabled() {
					return false;
				}

				public boolean isEnabled(int position) {
					return false;
				}
			};
			;
			setListAdapter(adapter);
		}
	}

}
